package xiaodong.train;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import xiaodong.train.bean.Settings;
import xiaodong.train.bean.UserInfo;

public class ObjectSerialization {

	static {
		File file = new File("config");
		if (!file.exists()) {
			file.mkdir();
		}
		if (!file.isDirectory()) {
			file.delete();
			file.mkdir();
		}
	}

	public void saveUserInfo(List<UserInfo> users) {
		try {
			ObjectOutputStream output = new ObjectOutputStream(
					new FileOutputStream("config/users.bin"));
			output.writeObject(users);
			output.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public List<UserInfo> readUserInfo() {
		List<UserInfo> list = new ArrayList<UserInfo>();
		try {
			ObjectInputStream input = new ObjectInputStream(
					new FileInputStream("config/users.bin"));
			list = (List<UserInfo>) input.readObject();
			System.out.println("读取到的用户信息数：" + list.size());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return list;
	}

	public void saveSettings(Settings setting) {
		try {
			ObjectOutputStream output = new ObjectOutputStream(
					new FileOutputStream("config/appconfig.bin"));
			output.writeObject(setting);
			output.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Settings readSettings() {
		Settings settings = null;
		try {
			ObjectInputStream input = new ObjectInputStream(
					new FileInputStream("config/appconfig.bin"));
			settings = (Settings) input.readObject();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return settings;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// 卞伟誉 210102198807143277 robots_gohome smiling99 yeah.net
		// TODO Auto-generated method stub

	}

}
